<template>
  <div class="config-detail" v-loading="loading">
    <!-- 错误信息显示 -->
    <div v-if="errorMessage" class="error-message">
      <el-alert
        :title="errorMessage"
        type="error"
        show-icon
        :closable="false"
      >
        <template slot="default">
          <div style="margin-top: 10px;">
            <el-button size="small" type="primary" @click="loadConfigDetail">重试</el-button>
          </div>
        </template>
      </el-alert>
    </div>
    
    <!-- 调试信息 -->
    <div v-if="!configInfo && !loading && !errorMessage" class="debug-info">
      <el-alert
        title="调试信息"
        :description="`配置ID: ${configId}, 加载状态: ${loading}, 数据: ${configInfo}`"
        type="info"
        show-icon
        :closable="false"
      />
    </div>
    
    <div v-if="configInfo">
      <!-- 基本信息 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">基本信息</span>
          <div class="header-tags">
            <el-tag v-if="configInfo.isDefault" type="success" size="medium">默认配置</el-tag>
            <el-tag :type="configInfo.status === '0' ? 'success' : 'danger'" size="medium">
              {{ configInfo.status === '0' ? '启用' : '禁用' }}
            </el-tag>
          </div>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>配置名称：</label>
              <span>{{ configInfo.configName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>算法类型：</label>
              <el-tag :type="getAlgorithmTagType(configInfo.algorithmType)">
                {{ getAlgorithmTypeText(configInfo.algorithmType) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ parseTime(configInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ configInfo.createBy || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="configInfo.updateTime">
          <el-col :span="12">
            <div class="info-item">
              <label>更新时间：</label>
              <span>{{ parseTime(configInfo.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>更新人：</label>
              <span>{{ configInfo.updateBy || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="configInfo.remark">
          <el-col :span="24">
            <div class="info-item">
              <label>备注：</label>
              <span>{{ configInfo.remark }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 算法参数 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">算法参数</span>
        </div>
        
        <div class="params-grid">
          <div class="param-item">
            <div class="param-label">种群大小</div>
            <div class="param-value">
              <el-progress
                :percentage="getPercentage(configInfo.populationSize, 10, 1000)"
                :show-text="false"
                color="#409EFF"
              ></el-progress>
              <span class="value-text">{{ configInfo.populationSize }}</span>
            </div>
            <div class="param-desc">算法中个体的数量，影响搜索的广度</div>
          </div>
          
          <div class="param-item">
            <div class="param-label">最大迭代次数</div>
            <div class="param-value">
              <el-progress
                :percentage="getPercentage(configInfo.maxGenerations, 10, 10000)"
                :show-text="false"
                color="#67C23A"
              ></el-progress>
              <span class="value-text">{{ configInfo.maxGenerations }}</span>
            </div>
            <div class="param-desc">算法的最大执行代数，控制搜索时间</div>
          </div>
          
          <div class="param-item">
            <div class="param-label">交叉概率</div>
            <div class="param-value">
              <el-progress
                :percentage="configInfo.crossoverRate * 100"
                :show-text="false"
                color="#E6A23C"
              ></el-progress>
              <span class="value-text">{{ configInfo.crossoverRate }}</span>
            </div>
            <div class="param-desc">个体间基因交换的概率，影响解的多样性</div>
          </div>
          
          <div class="param-item">
            <div class="param-label">变异概率</div>
            <div class="param-value">
              <el-progress
                :percentage="configInfo.mutationRate * 100"
                :show-text="false"
                color="#F56C6C"
              ></el-progress>
              <span class="value-text">{{ configInfo.mutationRate }}</span>
            </div>
            <div class="param-desc">个体基因发生变异的概率，防止早熟收敛</div>
          </div>
          
          <div class="param-item">
            <div class="param-label">精英保留比例</div>
            <div class="param-value">
              <el-progress
                :percentage="(configInfo.eliteRate || configInfo.elitismRate || 0) * 100"
                :show-text="false"
                color="#909399"
              ></el-progress>
              <span class="value-text">{{ configInfo.eliteRate || configInfo.elitismRate || 0 }}</span>
            </div>
            <div class="param-desc">每代保留的最优个体比例，保证解的质量</div>
          </div>
          
          <div class="param-item">
            <div class="param-label">收敛阈值</div>
            <div class="param-value">
              <el-progress
                :percentage="configInfo.convergenceThreshold * 100"
                :show-text="false"
                color="#606266"
              ></el-progress>
              <span class="value-text">{{ configInfo.convergenceThreshold }}</span>
            </div>
            <div class="param-desc">算法收敛的判断标准，控制停止条件</div>
          </div>
        </div>
      </el-card>
      
      <!-- 算法说明 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">算法说明</span>
        </div>
        
        <div class="algorithm-description">
          <div class="algorithm-info">
            <h4>{{ getAlgorithmTypeText(configInfo.algorithmType) }}</h4>
            <p>{{ getAlgorithmDescription(configInfo.algorithmType) }}</p>
          </div>
          
          <div class="algorithm-features">
            <h5>算法特点：</h5>
            <ul>
              <li v-for="feature in getAlgorithmFeatures(configInfo.algorithmType)" :key="feature">
                {{ feature }}
              </li>
            </ul>
          </div>
          
          <div class="algorithm-scenarios">
            <h5>适用场景：</h5>
            <ul>
              <li v-for="scenario in getAlgorithmScenarios(configInfo.algorithmType)" :key="scenario">
                {{ scenario }}
              </li>
            </ul>
          </div>
        </div>
      </el-card>
      
      <!-- 参数建议 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">参数建议</span>
        </div>
        
        <div class="param-suggestions">
          <el-alert
            v-for="suggestion in getParameterSuggestions(configInfo)"
            :key="suggestion.type"
            :title="suggestion.title"
            :description="suggestion.description"
            :type="suggestion.type"
            show-icon
            :closable="false"
            class="suggestion-item"
          />
        </div>
      </el-card>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" icon="el-icon-edit" @click="handleEdit">编辑配置</el-button>
        <el-button type="success" icon="el-icon-copy-document" @click="handleCopy">复制配置</el-button>
        <el-button
          v-if="!configInfo.isDefault"
          type="warning"
          icon="el-icon-star-off"
          @click="handleSetDefault"
        >设为默认</el-button>
        <el-button type="info" icon="el-icon-cpu" @click="handleTest">性能测试</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getAlgorithmConfig, setDefaultConfig, copyAlgorithmConfig } from '@/api/jwgl/algorithmConfig'
import { parseTime } from '@/utils'

export default {
  name: 'ConfigDetail',
  props: {
    configId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false,
      configInfo: null,
      errorMessage: null
    }
  },
  created() {
    this.loadConfigDetail()
  },
  watch: {
    configId: {
      handler(newId, oldId) {
        if (newId && newId !== oldId) {
          this.loadConfigDetail()
        }
      },
      immediate: false
    }
  },
  methods: {
    parseTime,
    /** 加载配置详情 */
    async loadConfigDetail() {
      this.loading = true
      this.errorMessage = null
      try {
        console.log('Loading config detail for ID:', this.configId)
        const response = await getAlgorithmConfig(this.configId)
        console.log('API response:', response)
        
        if (response && response.data) {
          this.configInfo = response.data
          console.log('Config info:', this.configInfo)
        } else {
          this.errorMessage = '服务器返回的数据格式不正确'
          console.error('Invalid response format:', response)
        }
      } catch (error) {
        console.error('Failed to load config detail:', error)
        this.errorMessage = `加载配置详情失败: ${error.message || error}`
        this.$modal.msgError('加载配置详情失败')
      } finally {
        this.loading = false
      }
    },
    
    /** 获取百分比 */
    getPercentage(value, min, max) {
      return Math.round(((value - min) / (max - min)) * 100)
    },
    
    /** 获取算法类型标签类型 */
    getAlgorithmTagType(type) {
      const typeMap = {
        'GENETIC': 'success',
        'SIMULATED_ANNEALING': 'warning',
        'PARTICLE_SWARM': 'info',
        'TABU_SEARCH': 'danger'
      }
      return typeMap[type] || 'info'
    },
    
    /** 获取算法类型文本 */
    getAlgorithmTypeText(type) {
      const typeMap = {
        'GENETIC': '遗传算法',
        'SIMULATED_ANNEALING': '模拟退火算法',
        'PARTICLE_SWARM': '粒子群优化算法',
        'TABU_SEARCH': '禁忌搜索算法'
      }
      return typeMap[type] || type
    },
    
    /** 获取算法描述 */
    getAlgorithmDescription(type) {
      const descriptions = {
        'GENETIC': '遗传算法是一种模拟自然选择和遗传机制的搜索算法，通过选择、交叉和变异操作来寻找最优解。适用于复杂的组合优化问题，具有较强的全局搜索能力。',
        'SIMULATED_ANNEALING': '模拟退火算法模拟固体退火过程，通过控制温度参数来平衡全局搜索和局部搜索。在高温时接受较差解，随着温度降低逐渐收敛到最优解。',
        'PARTICLE_SWARM': '粒子群优化算法模拟鸟群觅食行为，每个粒子根据自身经验和群体经验调整搜索方向。具有收敛速度快、参数少的特点。',
        'TABU_SEARCH': '禁忌搜索算法通过维护禁忌表来避免搜索过程中的循环，能够跳出局部最优解。适用于离散优化问题，搜索效率较高。'
      }
      return descriptions[type] || '暂无描述'
    },
    
    /** 获取算法特点 */
    getAlgorithmFeatures(type) {
      const features = {
        'GENETIC': [
          '全局搜索能力强，不易陷入局部最优',
          '适用于多目标优化问题',
          '对问题的数学性质要求较低',
          '具有良好的并行性'
        ],
        'SIMULATED_ANNEALING': [
          '能够跳出局部最优解',
          '算法简单，易于实现',
          '对初始解的依赖性较小',
          '收敛性有理论保证'
        ],
        'PARTICLE_SWARM': [
          '收敛速度快',
          '参数设置简单',
          '易于实现和理解',
          '适用于连续优化问题'
        ],
        'TABU_SEARCH': [
          '搜索效率高',
          '能够有效避免循环',
          '适用于离散优化',
          '局部搜索能力强'
        ]
      }
      return features[type] || []
    },
    
    /** 获取适用场景 */
    getAlgorithmScenarios(type) {
      const scenarios = {
        'GENETIC': [
          '大规模课程排课问题',
          '多约束条件的复杂排课',
          '需要平衡多个优化目标',
          '对解的质量要求较高'
        ],
        'SIMULATED_ANNEALING': [
          '中等规模的排课问题',
          '约束条件相对简单',
          '对计算时间有一定要求',
          '需要较好的解质量'
        ],
        'PARTICLE_SWARM': [
          '参数优化类排课问题',
          '连续性较强的优化目标',
          '需要快速收敛',
          '实时性要求较高'
        ],
        'TABU_SEARCH': [
          '离散型排课问题',
          '局部搜索效果明显',
          '需要避免重复搜索',
          '对搜索效率要求高'
        ]
      }
      return scenarios[type] || []
    },
    
    /** 获取参数建议 */
    getParameterSuggestions(config) {
      const suggestions = []
      
      // 种群大小建议
      if (config.populationSize < 50) {
        suggestions.push({
          type: 'warning',
          title: '种群大小偏小',
          description: '当前种群大小可能导致搜索多样性不足，建议增加到50-200之间以获得更好的搜索效果。'
        })
      } else if (config.populationSize > 500) {
        suggestions.push({
          type: 'info',
          title: '种群大小较大',
          description: '当前种群大小较大，可能增加计算时间，如果计算资源有限，可以适当减小。'
        })
      }
      
      // 交叉概率建议
      if (config.crossoverRate < 0.6) {
        suggestions.push({
          type: 'warning',
          title: '交叉概率偏低',
          description: '交叉概率过低可能影响算法的搜索能力，建议设置在0.6-0.9之间。'
        })
      }
      
      // 变异概率建议
      if (config.mutationRate > 0.3) {
        suggestions.push({
          type: 'warning',
          title: '变异概率偏高',
          description: '变异概率过高可能导致算法难以收敛，建议设置在0.01-0.3之间。'
        })
      }
      
      // 综合建议
      if (suggestions.length === 0) {
        suggestions.push({
          type: 'success',
          title: '参数配置合理',
          description: '当前参数配置在合理范围内，可以获得较好的优化效果。'
        })
      }
      
      return suggestions
    },
    
    /** 编辑配置 */
    handleEdit() {
      this.$emit('edit', this.configInfo)
    },
    
    /** 复制配置 */
    async handleCopy() {
      try {
        const { value } = await this.$prompt('请输入新配置名称', '复制配置', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: `${this.configInfo.configName}_副本`,
          inputPattern: /^.{2,100}$/,
          inputErrorMessage: '配置名称长度在2到100个字符之间'
        })
        
        await copyAlgorithmConfig(this.configId, value)
        this.$modal.msgSuccess('配置复制成功')
        this.$emit('refresh')
      } catch (error) {
        if (error !== 'cancel') {
          this.$modal.msgError('配置复制失败')
          console.error('复制配置失败:', error)
        }
      }
    },
    
    /** 设为默认 */
    async handleSetDefault() {
      try {
        await this.$modal.confirm(`确认将"${this.configInfo.configName}"设为默认配置？`, '设置默认配置', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await setDefaultConfig(this.configId, 1)
        this.$modal.msgSuccess('设置默认配置成功')
        this.loadConfigDetail()
        this.$emit('refresh')
      } catch (error) {
        if (error !== 'cancel') {
          this.$modal.msgError('设置默认配置失败')
          console.error('设置默认配置失败:', error)
        }
      }
    },
    
    /** 性能测试 */
    handleTest() {
      this.$modal.msgInfo('性能测试功能开发中')
    },
    
    /** 关闭 */
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.config-detail {
  .error-message,
  .debug-info {
    margin-bottom: 20px;
  }
  
  .detail-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .card-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
      
      .header-tags {
        .el-tag {
          margin-left: 8px;
        }
      }
    }
    
    .info-item {
      margin-bottom: 12px;
      
      label {
        font-weight: 500;
        color: #606266;
        margin-right: 8px;
        min-width: 80px;
        display: inline-block;
      }
      
      span {
        color: #303133;
      }
    }
  }
  
  .params-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    
    .param-item {
      padding: 16px;
      background-color: #f8f9fa;
      border-radius: 6px;
      
      .param-label {
        font-weight: 500;
        color: #303133;
        margin-bottom: 8px;
      }
      
      .param-value {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .el-progress {
          flex: 1;
          margin-right: 12px;
        }
        
        .value-text {
          font-weight: 600;
          color: #409EFF;
          min-width: 60px;
          text-align: right;
        }
      }
      
      .param-desc {
        font-size: 12px;
        color: #909399;
        line-height: 1.4;
      }
    }
  }
  
  .algorithm-description {
    .algorithm-info {
      margin-bottom: 20px;
      
      h4 {
        margin: 0 0 8px 0;
        color: #303133;
        font-size: 16px;
      }
      
      p {
        margin: 0;
        color: #606266;
        line-height: 1.6;
      }
    }
    
    .algorithm-features,
    .algorithm-scenarios {
      margin-bottom: 16px;
      
      h5 {
        margin: 0 0 8px 0;
        color: #303133;
        font-size: 14px;
        font-weight: 500;
      }
      
      ul {
        margin: 0;
        padding-left: 20px;
        
        li {
          color: #606266;
          line-height: 1.6;
          margin-bottom: 4px;
        }
      }
    }
  }
  
  .param-suggestions {
    .suggestion-item {
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .action-buttons {
    margin-top: 30px;
    text-align: right;
    border-top: 1px solid #e4e7ed;
    padding-top: 20px;
    
    .el-button {
      margin-left: 10px;
    }
  }
}
</style>